(function () {
    var exports = this;

    var $ = null;

    var HUTYPE_LIUJU = 0;
    var HUTYPE_ZIMO = 1;
    var HUTYPE_DIANPAO = 2;
    var HUTYPE_JIESANFANGJIAN = 3;

    var JiesuanLayerLLFY = cc.Layer.extend({
        onEnter: function () {
            cc.Layer.prototype.onEnter.call(this);
        },
        ctor: function (data) {
            this._super();

            var that = this;

            var size = cc.winSize;

            var scene;
            scene = loadNodeCCS(res["JiesuanLayerLLFY_json"], this);

            // this.addChild(scene.node);
            $ = create$(this.getChildByName("Scene"));

            var isZimo = (data['hu_type'] == HUTYPE_ZIMO);
            var isLiuju = (data['hu_type'] == HUTYPE_LIUJU);
            var isDianpao = (data['hu_type'] == HUTYPE_DIANPAO);
            var isJieSan = (data['hu_type'] == HUTYPE_JIESANFANGJIAN);
            var zhuangUid = data['zhuang'];
            var dianpaoUid = data['dianpao_uid'];
            var huPaiId = data['hu_pai_id'];
            var title = (data['map_id'] ? (gameData.mapId2Name[data['map_id']] + ' - ') || '' : '');

            if (false);
            else if (isLiuju)   title += '流局';
            else if (isZimo)    title += '自摸';
            else if (isDianpao) title += '点炮';
            else title += '解散';

            var btnFenxiang = $('root.panel.btn_fenxiang');
            var btnStart = $('root.panel.btn_start');
            var btnChakan = $('root.panel.btn_chakan');

            if (gameData.loginType == 'yk') {
                btnFenxiang.setVisible(false);
                btnStart.setPositionX(btnStart.getParent().getContentSize().width / 2);
                btnChakan.setPositionX(btnChakan.getParent().getContentSize().width / 2);
            }

            var players = data.players;

            var huCnt = 0;
            var diangangMap = {};
            for (var i = 0; i < players.length; i++) {
                var player = players[i];
                var isHu = player['hu'];
                if (isHu) {
                    huCnt += 1;
                }

                var duiArr = player['dui_arr'];
                for (var j = 0; j < duiArr.length; j++) {
                    var dui = duiArr[j];
                    if (dui['from_uid'] && dui['from_uid'] != player.uid) {
                        diangangMap[dui['from_uid']] = diangangMap[dui['from_uid']] || 0;
                        diangangMap[dui['from_uid']]++;
                    }
                }
            }

            var my_score = 0;
            var result = '';
            for (var i = 0; i < players.length; i++) {
                var player = players[i];
                var uid = player['uid'];
                var score = player['score'];
                var gangScore = player['gang_score'];
                var fan = player['fan'];
                var paiArr = player['pai_arr'];
                var dingArr = player['dingArr'];
                var duiArr = player['dui_arr'];
                var textArr = player['text_arr'];
                var isHu = player['hu'];

                var paiIdArr = [];

                if ($('root.panel.row' + i))
                    $('root.panel.row' + i).setVisible(true);

                if (!title && uid == gameData.uid)
                    title = (isHu ? '胡牌' : '失败');

                if (isHu) {
                    var idx = paiArr.indexOf(huPaiId);
                    if (idx >= 0) {
                        paiArr.splice(idx, 1);
                    }
                }

                var gouchengArr = [];

                var playerInfo = gameData.getPlayerInfoByUid(uid);
                $('root.panel.row' + i + '.lb_nickname').setString(ellipsisStr(playerInfo.nickname, 5));
                $('root.panel.row' + i + '.sp_zhuang').setVisible(zhuangUid == uid);
                // loadImageToSprite(playerInfo.headimgurl, $('root.panel.row' + i + '.head'));
                loadImage(playerInfo.headimgurl, $('root.panel.row' + i + '.head'), false);
                if (isDianpao) {
                    if(uid == dianpaoUid)
                        $('root.panel.row' + i + '.dianpao').setVisible(true);
                    else if(isHu)
                        $('root.panel.row' + i + '.hu').setVisible(true);
                } else if (isHu && isZimo) {
                    $('root.panel.row' + i + '.zimo').setVisible(true);
                } else if (isJieSan && isHu){
                    // $('root.panel.row' + i + '.hu').setVisible(true);
                }

                $('root.panel.row' + i + '.lb_score').setString(fan.toString());
                $('root.panel.row' + i + '.lb_score_gang').setString(gangScore.toString());
                $('root.panel.row' + i + '.lb_score_sum').setString(score < 0 ? score : ('+' + score.toString()));

                if (uid == gameData.uid) my_score = score;

                if (uid == gameData.uid) {
                    if (score < 0) {
                        result = 'shule';
                    } else if (score > 0) {
                        result = 'yingle';
                    } else {
                        result = 'ping';
                    }
                }
                while (true) {
                    for (var j = 0; j < duiArr.length; j++) {
                        var dui = duiArr[j];
                        if (dui.type == 5)
                            break;
                    }
                    if (j == duiArr.length)
                        break;
                    paiArr.push(duiArr[j]['pai_arr'][0]);
                    paiArr.push(duiArr[j]['pai_arr'][0]);
                    paiArr.push(duiArr[j]['pai_arr'][0]);
                    duiArr.splice(j, 1);
                }

                _.remove(paiArr, function (n) {
                    return n == 0;
                });

                paiArr.sort(function (a, b) {
                    return a - b
                });
                duiArr.sort(function (a, b) {
                    if (a['pai_arr'][0] == b['pai_arr'][0]) {
                        if (a['pai_arr'][1] == b['pai_arr'][1])
                            return a['pai_arr'][2] - b['pai_arr'][2];
                        return a['pai_arr'][1] - b['pai_arr'][1];
                    }
                    return a['pai_arr'][0] - b['pai_arr'][0];
                });

                var a0 = $('root.panel.row' + i + '.a' + 0);
                var anGangCnt = 0;
                var gangCnt = 0;
                for (var j = 0; j < duiArr.length; j++) {
                    var dui = duiArr[j];
                        if (dui.type == 1) {
                            paiIdArr.push(dui['pai_arr'][0]);
                            paiIdArr.push(dui['pai_arr'][1]);
                            paiIdArr.push(dui['pai_arr'][2]);
                        }
                        if (dui.type == 2) {
                            paiIdArr.push(dui['pai_arr'][0]);
                            paiIdArr.push(dui['pai_arr'][0]);
                            paiIdArr.push(dui['pai_arr'][0]);
                        }
                        if (dui.type == 3) {
                            paiIdArr.push(dui['pai_arr'][0]);
                            paiIdArr.push(dui['pai_arr'][0]);
                            paiIdArr.push(dui['pai_arr'][0]);
                            paiIdArr.push(dui['pai_arr'][0]);
                            gangCnt++;
                        }
                        if (dui.type == 4) {
                            paiIdArr.push(0);
                            paiIdArr.push(0);
                            paiIdArr.push(0);
                            paiIdArr.push(dui['pai_arr'][0]);
                            anGangCnt++;
                        }

                    paiIdArr.push(-1);
                }

                if (anGangCnt)
                    gouchengArr.push("暗杠" + (anGangCnt > 1 ? 'x' + anGangCnt : ''));

                if (gangCnt)
                    gouchengArr.push("明杠" + (gangCnt > 1 ? 'x' + gangCnt : ''));

                if (diangangMap[uid])
                    gouchengArr.push("点杠" + (diangangMap[uid] > 1 ? 'x' + diangangMap[uid] : ''));

                for (var j = 0; j < paiArr.length; j++) {
                    paiIdArr.push(paiArr[j]);
                }

                if (isHu && huPaiId) {
                    if (paiIdArr[paiIdArr.length - 1] != -1)
                        paiIdArr.push(-1);
                    paiIdArr.push(huPaiId);

                    gouchengArr.push(isZimo ? '自摸' : '点炮胡');
                } else {
                    $('root.panel.row' + i + '.lb_score').setVisible(true);
                }

                if (uid == dianpaoUid) {
                    gouchengArr.push('点炮' + (huCnt > 1 ? 'x' + huCnt : ''));
                }

                if (textArr) {
                    gouchengArr = [];
                    for (var j = 0; j < textArr.length; j++) {
                        var obj = textArr[j];
                        for (var key in obj)
                            gouchengArr.push(decodeURIComponent(key) + (obj[key] > 1 ? 'x' + obj[key] : ''));
                    }
                }

                gouchengArr.sort(function (a, b) {
                    return a < b
                });
                $('root.panel.row' + i + '.lb_goucheng').setString(gouchengArr.join(" "));

                var gapNum = 0;
                var gapDistance = 20;
                if (player.uid == gameData.uid) {
                    $('root.panel.row' + i + '.bg').setVisible(true);
                }
                for (var j = 0; j < paiIdArr.length; j++) {
                    if (paiIdArr[j] == -1) {
                        gapNum++;
                        continue;
                    }
                    var pai = $('root.panel.row' + i + '.a' + j);
                    if (!pai) {
                        pai = duplicateNode(a0);
                        pai.setPositionX(a0.getPositionX() + a0.getContentSize().width * 0.932 * a0.getScaleX() * (j - gapNum) + gapNum * gapDistance);
                        a0.getParent().addChild(pai);

                    }

                    var paiName = 'p2s' + paiIdArr[j] + '.png';
                    setSpriteFrameByName(pai, paiName, 'pai');
                    var lb_liang = cc.textureCache.addImage(res.lb_liang);
                    var lb = pai.getChildByName('lb');
                    if(lb) {
                        lb.setVisible(false);
                    }
                    for(var m=0;m<dingArr.length;m++) {
                        if(paiIdArr[j]==dingArr[m]) {
                            Filter.grayMask(pai);
                            if (!lb) {
                                lb = new cc.Sprite(res.lb_liang);
                                lb.setTexture(lb_liang);
                                lb.setName('lb');
                                pai.addChild(lb);
                                lb.setPosition(17.1, 21.5);
                            }
                            else
                                lb.setTexture(lb_liang);
                            lb.setVisible(true);
                            delete dingArr[m];
                            break;
                        }
                    }
                }
            }
            result = isLiuju ? 'liuju' : result;

            $('root.panel.lb_ts').setString(timestamp2time(data['ts']));

            if (isJieSan){
                $('root.panel.title_fail_bg').setVisible(true);
                $('root.panel.title_fail_bg.title_jiesan').setVisible(true);
            } else if (isLiuju) {
                $('root.panel.title_fail_bg').setVisible(true);
                $('root.panel.title_fail_bg.title_liuju').setVisible(true);
            } else if (my_score > 0) {
                $('root.panel.title_win_bg').setVisible(true);
            } else {
                $('root.panel.title_fail_bg').setVisible(true);
                $('root.panel.title_fail_bg.title_zjzl').setVisible(true);
            }
            $('root.panel.lb_roomid').setString('房间号: ' + gameData.roomId + ' 局数: ' + data['cur_round'] + '/' + data['total_round']);

            for (var i = players.length; i < 4; i++)
                $('root.panel.row' + i).setVisible(false);

            TouchUtil.setOnclickListener(btnFenxiang, function () {
                ShareUtil.SharePic(that);
            });

            TouchUtil.setOnclickListener(btnStart, function () {
                // ready
                network.send(3004, {room_id: gameData.roomId});
                window.maLayer.onJiesuanClose(true);
                that.removeFromParent(true);
            });

            var closeFunc = function () {
                // ready
                window.maLayer.onJiesuanClose(false);
                that.removeFromParent(true);
            };
            TouchUtil.setOnclickListener($('root.panel.btn_close'), closeFunc);
            TouchUtil.setOnclickListener(btnChakan, closeFunc);

            if (data['is_last']) {
                btnStart.setVisible(false);
                btnChakan.setVisible(true);
            }

            return true;
        }
    });

    exports.JiesuanLayerLLFY = JiesuanLayerLLFY;
})(window);
